/**
 * =========================== 通用网络请求方法 ===========================
 */

//加入下面的代码

/**
 统一支付方法
type 1.微信支付 100.余额支付
payPassword 余额支付的时候才有这个值
*/
function connectBle(params) {

	//打开蓝牙适配器
	uni.openBluetoothAdapter({
		success(res) {
			console.log(res)
			// 以微信硬件平台的蓝牙智能灯为例，主服务的 UUID 是 FEE7。传入这个参数，只搜索主服务 UUID 为 FEE7 的设备
			uni.startBluetoothDevicesDiscovery({
				success(res) {
					console.log(res)
				}
			})
		}
	})
	//扫描设备
	uni.onBluetoothDeviceFound(function(devices) {
		// console.log('new device list has founded')
		const name = devices.devices[0].name;
		const deviceId = devices.devices[0].deviceId;
		// console.log(devices)
		// console.log(name + " " + deviceId)
		if ('SZ' == name) {
			console.log("找到硬件设备")
			//停止搜索
			uni.stopBluetoothDevicesDiscovery({
				success(res) {
					console.log(res)
				}
			})
			//建立连接
			uni.createBLEConnection({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId,
				success(res) {
					console.log("建立连接" + JSON.stringify(res))

					typeof params.success == "function" && params.success(deviceId, "建立成功");
				}
			})

		} else {
			// typeof params.error == "function" && params.error("未找到蓝牙设备");
		}
		// console.log(_this.ab2hex(devices[0].advertisData))
	})
	//监听蓝牙连接状态
	uni.getConnectedBluetoothDevices({
		success(res) {
			console.log(res)
		}
	})

}

//连接到特征通道
function connectCharacteristic(params) {
	console.log("开始建立通道")
	//开始订阅
	const deviceId = params.deviceId;
	const serviceId = params.serviceId;
	const characteristicId = params.characteristicId;
	console.log(deviceId + "   " + serviceId + "  " + characteristicId)
	//开始监听订阅
	uni.notifyBLECharacteristicValueChange({
		state: true, // 启用 notify 功能
		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
		deviceId,
		// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
		serviceId,
		// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
		characteristicId,
		success(res) {
			console.log('notifyBLECharacteristicValueChange success', res.errMsg)
			uni.setStorageSync('deviceId', deviceId);
			typeof params.success == "function" && params.success("通道建立成功");
		}
	})

	//特征值变化监听
	uni.onBLECharacteristicValueChange(function(res) {
		// console.log(JSON.stringify(res))
		// console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
		// console.log(ab2hex(res.value))
		typeof params.change == "function" && params.change(ab2hex(res.value));
	})
	//状态监听
	uni.onBLEConnectionStateChange(function(res) {
		// 该方法回调中可以用于处理连接意外断开等异常情况
		//下面一行打印的结果 device 61:6B:12:A8:AF:C4 state has changed, connected: false at js/BleUtils.js:101
		console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
		if (!res.connected) {
			stopConnection()
		}
	})

}

function ab2hex(buffer) { //转16进制
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('')
}

function hex2int(hex) { //16进制转10进制
	var len = hex.length,
		a = new Array(len),
		code;
	for (var i = 0; i < len; i++) {
		code = hex.charCodeAt(i);
		if (48 <= code && code < 58) {
			code -= 48;
		} else {
			code = (code & 0xdf) - 65 + 10;
		}
		a[i] = code;
	}

	return a.reduce(function(acc, c) {
		acc = 16 * acc + c;
		return acc;
	}, 0);
}

function stopConnection() {
	const deviceId = uni.getStorageSync('deviceId');
	if (deviceId != null && deviceId.length > 0) { //关闭通道连接
		uni.closeBLEConnection({
			deviceId,
			success(res) {
				console.log("关闭通道")
				console.log(res)
			}
		})
	}
	//关闭蓝牙适配器
	uni.closeBluetoothAdapter({
		success(res) {
			console.log("关闭蓝牙适配器")
			console.log(res)
		}
	})
}


function transferTemperature(data) { //传入电压数据计算温度结果,传入data传入16进制的数据

	data = hex2int(data+"")
	console.log("data  " + data)
	let AD = 7
	let r = data - AD
	r = r / 22;
	r = r * 9.96

	let resTemp = 0;
	if (40.16 <= r && r < 79.5368) {
		resTemp = 0.0038 * r * r - 0.8334 * r + 57.323;
	} else if (32.525 <= r && r < 40.16) {
		resTemp = 0.0105 * r * r - 1.4136 * r + 69.916;
	} else if (26.527 <= r && r < 32.525) {
		resTemp = 0.0164 * r * r - 1.8022 * r + 76.237;
	} else if (21.716 <= r && r < 26.527) {
		resTemp = 0.0254 * r * r - 2.2667 * r + 82.222;
	}
	return resTemp.toFixed(1)
}


module.exports = {
	connectBle: connectBle,
	connectCharacteristic: connectCharacteristic,
	stopConnection: stopConnection,
	transferTemperature: transferTemperature
}
